using System;
using Habanero.Base;
using Habanero.Base.Exceptions;
using Habanero.BO;

namespace FireStarterModeller.BO
{
    public class DMClassDuplicateRelationshipNameRule : IBusinessObjectRule
    {
        private DMClass _dmClass;
        private string _relationshipName;

//        public DMClassDuplicateRelationshipNameRule(DMClass dmClass)
//        {
//            if (dmClass == null) throw new ArgumentNullException("dmClass");
//            _dmClass = dmClass;
//        }

        public bool IsValid()
        {
            throw new HabaneroApplicationException("The IsValid is no longer Valid you should use the IsValid(bo) method");
        }

        public bool IsValid(IBusinessObject bo)
        {
            _dmClass = (DMClass) bo;
            if (_dmClass.OwnerRelationships.Count < 2) return true;
            BusinessObjectCollection<DMRelationship> ownerRelationships = _dmClass.OwnerRelationships;
            ownerRelationships.Sort("RelationshipName", true, true);
            string previousRelName = "";
            foreach (DMRelationship dmRelationship in ownerRelationships)
            {
                if (String.IsNullOrEmpty(dmRelationship.RelationshipName)) continue;
                if (dmRelationship.RelationshipName.Equals(previousRelName))
                {
                    _relationshipName = previousRelName;
                    return false;
                }
                previousRelName = dmRelationship.RelationshipName;
            }
            return true;
        }

        public string Name
        {
            get { return "DMClassDuplicateRelationshipName"; }
        }

        public string Message
        {
            get
            {
                return "The Entity/Class '" + _dmClass +
                       "' cannot have more than one relationship with the same name('" + _relationshipName + "').";
            }
        }

        public ErrorLevel ErrorLevel
        {
            get { return ErrorLevel.Warning; }
        }
    }
}